import store from '../store/'
// import Vue from 'vue'
import {UPDATA_INTERACTIVE,PUSH_MWSSAGENOTIFY, PUSH_WINNOTICE} from '../store/interactive'
import {CLEAR_MWSSAGENOTIFY} from "store/interactive";
import {IS_UPDAADDRESSTELIST} from "store/address";


var u = navigator.userAgent;
var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
function setupWebViewJavascriptBridge(callback) {
    if (isiOS) {
        if (window.WebViewJavascriptBridge) {
            return callback(WebViewJavascriptBridge);
        }
        if (window.WVJBCallbacks) {
            return window.WVJBCallbacks.push(callback);
        }
        window.WVJBCallbacks = [callback];
        var WVJBIframe = document.createElement('iframe');
        WVJBIframe.style.display = 'none';
        WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__';
        document.documentElement.appendChild(WVJBIframe);
        setTimeout(function () {
            document.documentElement.removeChild(WVJBIframe)
        }, 0)
    } else if (isAndroid) {
        if (window.WebViewJavascriptBridge) {
            callback(WebViewJavascriptBridge)
        } else {
            document.addEventListener(
                'WebViewJavascriptBridgeReady'
                , function () {
                    callback(WebViewJavascriptBridge)
                },
                false
            );
        }
    }

}

//移动端调用H5
setupWebViewJavascriptBridge(function (bridge) {
    if (isAndroid) {
        bridge.init(function (message, responseCallback) {
            console.log('JS got a message', message);
            responseCallback(data);
        });
    }
    bridge.registerHandler('userLoginSucc', function (data, responseCallback) {
        let token = data.token;
        let inviteCode = data.inviteCode;
        if (isAndroid) {
            token = JSON.parse(data).token;
            inviteCode = JSON.parse(data).inviteCode
        }
        Vue.prototype.comJS.setCookie("t", token,15);
        Vue.prototype.comJS.setCookie("inviteCode",inviteCode,15);
        store.commit(UPDATA_INTERACTIVE, {type: 'refreshMyPage', content: {type:true,flag:'ok'}});
        store.commit(UPDATA_INTERACTIVE, {type: 'refreshUserInfo', content: {flang:true}});
        store.commit(IS_UPDAADDRESSTELIST, true);
        Vue.prototype.comJS.openMask();
        responseCallback('js执行过了');
    });
    bridge.registerHandler('userLoginOut', function (data, responseCallback) {
        window.localStorage.clear();
        // Vue.prototype.comJS.setCookie("t", 0 ,-1);
        store.commit(UPDATA_INTERACTIVE, {type: 'refreshMyPage', content: {type:true,flag:'out'}});
        store.commit(IS_UPDAADDRESSTELIST, true);
        store.commit(CLEAR_MWSSAGENOTIFY);
        responseCallback('js执行过了');
    });
    bridge.registerHandler('pushTokenToJs', function (data, responseCallback) {
        let token = data.token;
        let inviteCode = data.inviteCode;
        if (isAndroid) {
            token = JSON.parse(data).token;
            inviteCode = JSON.parse(data).inviteCode
        }
      console.log('??????????????????????????????????????????????????????','检测到移动端交互方法传入token',  new Date())
        Vue.prototype.comJS.setCookie("t",token,15);
        Vue.prototype.comJS.setCookie("inviteCode",inviteCode,15);
        if(token){
          Vue.prototype.comJS.getUserInfo();
        }
        Vue.prototype.comJS.openMask();
        if(token){
            store.commit(UPDATA_INTERACTIVE, {type: 'refreshMyPage', content: {type:true,flag:'ok'}});
            store.commit(UPDATA_INTERACTIVE, {type: 'refreshUserInfo', content: {flang:true}});
        }else{
            store.commit(UPDATA_INTERACTIVE, {type: 'refreshMyPage', content: {type:false,flag:'ok'}});
        }
        responseCallback('js执行过了');
    });
    bridge.registerHandler('uploadPictureSucc', function (data, responseCallback) {
        if (isAndroid) {
            data = JSON.parse(data);
        }
        store.commit(UPDATA_INTERACTIVE, {type: 'image', content:{url:data}});
        responseCallback('js执行过了');
    });
    bridge.registerHandler('pushLatlngToJs', function (data, responseCallback) {
        if (isAndroid) {
            data = JSON.parse(data);
        }
        console.log("安卓推送经纬度---" + JSON.stringify(data) + '----------' + new Date())
        /*Vue.$vux.alert.show({
          title:'',
          content:"安卓推送经纬度---" + JSON.stringify(data)
        })*/
        let locationType = 'Location'
        if(window.localStorage.getItem('locationType') == 'LocationByDetail'){
          locationType = 'LocationByDetail'
        }
      if(window.localStorage.getItem('locationType') == 'LocationByAddress'){
        locationType = 'LocationByAddress'
      }
        if(data.lo == 0 || data.la == 0){
            if(localStorage.hasOwnProperty('address') && !!(JSON.parse(localStorage.address).content)){
                var str,recipientsDistrict
                JSON.parse(localStorage.address).content.forEach((v)=>{
                    if(v.isDefault == 1){
                        str = v.recipientsProvince + v.recipientsCity + v.recipientsDistrict + v.recipientsDetailAddress
                      recipientsDistrict = v.recipientsDistrict
                    }
                })
                Vue.prototype.comJS.locationToCode(str)
                    .then(res => {
                        var arr = res.split(',')
                        store.commit(UPDATA_INTERACTIVE, {type: locationType, content:{lo:arr[0],la:arr[1],addressText:recipientsDistrict}});
                    })
            } else {
                store.commit(UPDATA_INTERACTIVE, {type: locationType, content:{lo:121.426557,la:31.157329,addressText:'上海市'}});
            }

        } else {
          store.commit(UPDATA_INTERACTIVE, {type: locationType, content:data});
        }
        responseCallback('js执行过了');
    });
    bridge.registerHandler('callNavBarAndTabBarHeight', function (data, responseCallback) {
        if (isAndroid) {
            data = JSON.parse(data);
        }
        // alert("获取原生NavBar高度" + data.navHeight + "px-------tabBar高度" + data.tabBarHeight+ "px")
        store.commit(UPDATA_INTERACTIVE, {type: 'statusBarHeight', content: {height: parseInt(data.navHeight)/100 + 'rem',tabBarHeight:parseInt(data.tabBarHeight)>100?parseInt(data.tabBarHeight)/100 - 1 + 'rem':'0' }});
        responseCallback('js执行过了');

    });
    bridge.registerHandler('weChatAuthState', function (data, responseCallback) {
        if (isAndroid) {
            data = JSON.parse(data);
        }
        store.commit(UPDATA_INTERACTIVE, {type: 'wx_info', content: data.wexinResp});
        responseCallback('js执行过了');

    });
    bridge.registerHandler('weChatPayNotify', function (data, responseCallback) {
        // alert(JSON.stringify(data));
        if (isAndroid) {
            data = JSON.parse(data);
        }
        /*if (!isAndroid) {
            alert("支付回调----"+JSON.stringify(data));
        }*/
        store.commit(UPDATA_INTERACTIVE, {type: 'payStatus', content: data});
        responseCallback('js执行过了');

    });
    bridge.registerHandler('alipayPayNotify', function (data, responseCallback) {
        // alert(JSON.stringify(data));
        if (isAndroid) {
            data = JSON.parse(data);
        }

        store.commit(UPDATA_INTERACTIVE, {type: 'payStatus', content: data});
        responseCallback('js执行过了');

    });
    bridge.registerHandler('jpushMessageNotify', function (data, responseCallback) {
        let obj = data.extraParams;
        if (isAndroid) {
            obj = JSON.parse(JSON.parse(data).extraParams);
        }
        alert(JSON.stringify(obj))
        if(obj && obj != null){
            if(obj.subType != '50102'){
                store.commit(PUSH_MWSSAGENOTIFY,obj);
            } else {
                store.commit(PUSH_WINNOTICE,obj);
            }
        }
        responseCallback('js执行过了');

    });
    bridge.registerHandler('pushShopDetails', function (data, responseCallback) {
        alert(JSON.stringify(data));
        if (isAndroid) {
            data = JSON.parse(data);
        }
        store.commit(UPDATA_INTERACTIVE, {type: 'pushShopDetails', content: data});

        responseCallback('js执行过了');

    });
    bridge.registerHandler('getChannel', function (data, responseCallback) {
        if (isAndroid) {
            data = JSON.parse(data);
        }
        store.commit(UPDATA_INTERACTIVE, {type: 'as', content: data});

        responseCallback('js执行过了');
    });
    bridge.registerHandler('qyUnReadMsgCount', function (data, responseCallback) {  //七鱼未读消息获取
        if (isAndroid) {
            data = JSON.parse(data);
        }
        data.qyMsgCount = parseInt(data.qyMsgCount);
        store.commit(UPDATA_INTERACTIVE, {type: 'qyMsgCount', content: data});
        store.commit(UPDATA_INTERACTIVE, {type: 'checkIsNewEdition', content: {type:true}});
        responseCallback('js执行过了');
    });
    bridge.registerHandler('qyUnReadMsgCount', function (data, responseCallback) {  //七鱼未读消息获取
        if (isAndroid) {
            data = JSON.parse(data);
        }
        data.qyMsgCount = parseInt(data.qyMsgCount);
        store.commit(UPDATA_INTERACTIVE, {type: 'qyMsgCount', content: data});
        store.commit(UPDATA_INTERACTIVE, {type: 'checkIsNewEdition', content: {type:true}});
        responseCallback('js执行过了');
    });
    bridge.registerHandler('pushAppVersionToJs', function (data, responseCallback) {
        if (isAndroid) {
            data = JSON.parse(data);
        }
        store.commit(UPDATA_INTERACTIVE, {type: 'versionName', content: data});
        responseCallback('js执行过了');
    });
    bridge.registerHandler('openQyNativeChat', function (data, responseCallback) {
        if (isAndroid) {
            data = JSON.parse(data);
        }
        store.commit(UPDATA_INTERACTIVE, {type: 'isnativeqy', content: data});
        responseCallback('js执行过了');
    });
    bridge.registerHandler('startWave', function (data, responseCallback) {
        store.commit(UPDATA_INTERACTIVE, {type: 'startWave', content: {startWave:true}});
        responseCallback('js执行过了');
    });

})

//H5调用移动端
const Interactive = {
    isMyApp: true,
    getChannel: function () {  //初始化时获取加载渠道来源（安卓，iOS，浏览器）（0：安卓 1：iOS）
        if (!this.isMyApp) {
            return;
        }
        return;  //取消
        alert("开始给获取加载渠道");
        WebViewJavascriptBridge.callHandler('getChannel', null, function (response) {
            if (isAndroid) {
                response = JSON.parse(response);
            }
            alert("获取加载渠道结束"+JSON.stringify(response));
            store.commit(UPDATA_INTERACTIVE, {type: 'as', content: response});

        })
    },
    getUserToken: function () {  //获取个人token
        if (!this.isMyApp) {
            return;
        }
        WebViewJavascriptBridge.callHandler('getUserToken', null, function (response) {
            let token = response.token;
            if (isAndroid) {
                token = JSON.parse(response).token;
            }
            Vue.prototype.comJS.setCookie("t", token,15);

            if(token){
                store.commit(UPDATA_INTERACTIVE, {type: 'refreshMyPage', content: {type:true,flag:'ok'}});
            }else{
                store.commit(UPDATA_INTERACTIVE, {type: 'refreshMyPage', content: {type:false,flag:'ok'}});
            }
        })
    },
    pushTokentoJS: function () { //获取个人token并跳转登录页面
        if (!this.isMyApp) {
            return;
        }
        WebViewJavascriptBridge.callHandler('userLogin', null, function (response) {
            let token = response.token;
            if (isAndroid) {
                token = JSON.parse(response).token;
            }
            alert(token);
            // alert("userLogin----" + token)
            Vue.prototype.comJS.setCookie("t", token,15);
        })
    },
    userSettingClick: function () {  //用户点击设置按钮
        if (!this.isMyApp) {
            return;
        }
        WebViewJavascriptBridge.callHandler('userSettingClick', null, function (response) {
        })
    },
    hiddenTabbar: function () {  //原生隐藏tab
        if (!this.isMyApp) {
            return;
        }
        WebViewJavascriptBridge.callHandler('hiddenTabbar', null, function (response) {
        })
    },
    showTabbar: function () {  //原生显示tab
        if (!this.isMyApp) {
            return;
        }
        WebViewJavascriptBridge.callHandler('showTabbar', null, function (response) {
        })
    },
    uploadPictures: function (num,canEdit) {  //上传图片    canEdit 如果为真的话代表需要裁剪
        if (!this.isMyApp) {
            return;
        }
        WebViewJavascriptBridge.callHandler('uploadPictures', {type:num,canEdit:canEdit?'YES':'NO'}, function (response) {
            if (isAndroid) {
                response = JSON.parse(response);
            }
            alert(JSON.stringify(response));
            store.commit(UPDATA_INTERACTIVE, {type: 'image', content:{url:response.imageLocalPath}});
        })

    },
    recommendMapClick: function () {  //进入异业联盟地图版
        if (!this.isMyApp) {
            return;
        }
        alert("进入异业联盟地图版");
        WebViewJavascriptBridge.callHandler('recommendMapClick', null, function (response) {
        })

    },
    sweepClickInRecommend: function () {  //进入异业联盟扫一扫
        if (!this.isMyApp) {
            return;
        }
        alert("进入异业联盟扫一扫");
        WebViewJavascriptBridge.callHandler('sweepClickInRecommend', null, function (response) {
        })

    },
    shareClick: function (obj) {  //分享
        if (!this.isMyApp) {
            return;
        }
        let shareObj = {
            "title": obj.title,
            "content": obj.content,
            "imageUrl": obj.imageUrl,
            "shareUrl": obj.shareUrl,
            "originalPage": obj.originalPage
        }
        WebViewJavascriptBridge.callHandler('shareClick', shareObj, function (response) {
        })
    },
    getLocation: function (callback) { //获取定位
        if (!this.isMyApp) {
            return;
        }
      console.log("向移动端要位置---" + '----------' + new Date())

      WebViewJavascriptBridge.callHandler('getLocation', null, function (response) {
        })
    },
    weChatAuth: function () { //我的资料页面同步微信资料
        if (!this.isMyApp) {
            return;
        }
        alert('同步资料到微信-开始');
        WebViewJavascriptBridge.callHandler('weChatAuth', null, function (response) {
        })
    },
    weChatPay: function (obj) { //H5选择微信支付()
        if (!this.isMyApp) {
            return;
        }
        alert("微信")
        alert(JSON.stringify(obj))
        WebViewJavascriptBridge.callHandler('weChatPay', obj, function (response) {
        })
    },
    alipayPay: function (obj) { //H5选择支付宝

        if (!this.isMyApp) {
            return;
        }
        alert("支付宝")
        WebViewJavascriptBridge.callHandler('alipayPay', obj, function (response) {
        })
    },
    makePhoneCall:function (obj) {
        if (!this.isMyApp) {
            return;
        }
        WebViewJavascriptBridge.callHandler('makePhoneCall', obj, function (response) {
        })
    },
    changeStatusStyle:function (type) {  //1代表白色，0代表黑色
        if (!this.isMyApp) {
            return;
        }
        WebViewJavascriptBridge.callHandler('changeStatusStyle', {statusStyle:type}, function (response) {
            if (isAndroid) {
                response = JSON.parse(response);
            }
        })
    },
    getAppReviewState:function (callback) { //获取iOS app状态 isReview为1时，进入iOS内购（原生处理），为0时进入第三方充值页面（H5处理）
        if (!this.isMyApp || isAndroid) {
            callback();
            return;
        }
        WebViewJavascriptBridge.callHandler('getAppReviewState', null, function (response) {
            alert(response.isReview )
            if(response.isReview == "0"){
                callback();
            }
        })
    },
    showQrCodeDetails:function (obj) { //跳转到原生商家二维码详情页面
        WebViewJavascriptBridge.callHandler('showQrCodeDetails', obj, function (response) {
        })
    },
    backMapMerchants:function () {  //地图版商家联盟进入详情后，点击返回按钮事件
        alert("开始调用backMapMerchants")
        WebViewJavascriptBridge.callHandler('backMapMerchants', null, function (response) {
        })
    },
    orderDetailIntoHome:function () {
        alert("订单中详情页返回首页")
        WebViewJavascriptBridge.callHandler('orderDetailIntoHome', null, function (response) {
        })
    },
    activityWebDismiss:function () {
        alert("从外部（微信，qq，浏览器进入APP），点击H5导航根返回键");
        window.localStorage.clear();
        WebViewJavascriptBridge.callHandler('activityWebDismiss', null, function (response) {

        })
    },
    intoActivityWebView:function (title,url) {
        WebViewJavascriptBridge.callHandler('intoActivityWebView', {title:title,url:url}, function (response) {
        })
    },
    copyToClipboard:function (copyName) {
        WebViewJavascriptBridge.callHandler('copyToClipboard', {copyName:copyName}, function (response) {
        })
    },
    openServiceChat:function (data) {  //
        let int = 1;
        let arr = Object.keys(data);
        arr.forEach((v)=>{
            if(v != "orderId"){
                if(!data[v] ||data[v] == null){
                    int = -1
                }
            }
        })
        if(int == 1){
            WebViewJavascriptBridge.callHandler('openServiceChat', {crmParams:{"entrance":data.entrance,"name":data.name,"mobile":data.mobile,"gender":data.gender,"orderId":data.orderId,"avatar":data.avatar,"groupId":data.groupId}}, function (response) {
            })
        }

    },
    customStatistics:function(data){
        // return;
        //     alert(JSON.stringify({type:data.type,eventID: data.eventID, label: data.label || null,map: JSON.stringify(data.map) || null}))
            WebViewJavascriptBridge.callHandler('customStatistics', {type:data.type,eventID: data.eventID, label: data.label || null,map: JSON.stringify(data.map) || null}, function (response) {
                alert(JSON.stringify(response))
            })
    },

    //登录失效推送移动端
  loginOut: function () {
    WebViewJavascriptBridge.callHandler('loginOut',function (response) {
      localStorage.removeItem('t')
    })
  },
  shareMiniProgram:function (obj) {  //分享小程序
    if (!this.isMyApp) {
      return;
    }
    let shareObj = {
      "title": obj.title,
      "content": obj.content,
      "imageUrl": obj.imageUrl,
      "originalPage": obj.originalPage
    }
    WebViewJavascriptBridge.callHandler('shareMiniProgram', shareObj, function (response) {
    })
  },
    productImageClick:function(imageUrls,index){  //画廊
        if (!this.isMyApp) {
            return;
        }
        let obj = {
            imageUrls:imageUrls,
            index:index
        }
        WebViewJavascriptBridge.callHandler('productImageClick', obj, function (response) {
        })
    },
    callSystemVibrate:function () {  // 震动
        if (!this.isMyApp) {
            return;
        }
        WebViewJavascriptBridge.callHandler('callSystemVibrate', null, function (response) {
        })
    },
    listenToShake(){   //原生开始监测摇一摇
        if (!this.isMyApp) {
            return;
        }
        WebViewJavascriptBridge.callHandler('listenToShake', null, function (response) {
        })
    },
    stopListenToShake(){   //原生停止监测摇一摇
        if (!this.isMyApp) {
            return;
        }
        WebViewJavascriptBridge.callHandler('stopListenToShake', null, function (response) {
        })
    }

}

export default {
    install: function (Vue, option) {
        Vue.prototype.Interactive = Interactive;
    }
}